package org.jeecg.modules.lab.entrust.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.TemplateException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.cronJob.MyEnum;
import org.jeecg.common.cronJob.entity.LabCronJob;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.TokenServess;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.lab.cronJob.service.ILabCronJobService;
import org.jeecg.modules.lab.entrust.entity.*;
import org.jeecg.modules.lab.entrust.service.*;
import org.jeecg.modules.lab.entrust.vo.LabEntrustAnaPageA;
import org.jeecg.modules.lab.entrust.vo.LabEntrustAnaPageB;
import org.jeecg.modules.lab.entrust.vo.LabEntrustPage;
import org.jeecg.modules.lab.items.record.service.*;
import org.jeecg.modules.lab.items.task.service.ILabTaskAllotService;
import org.jeecg.modules.lab.items.vo.LabAdutiUserPage;
import org.jeecg.modules.lab.items.vo.LabEntrustItemsIndexPage;
import org.jeecg.modules.lab.items.vo.LabSampleRecordPage;
import org.jeecg.modules.lab.notify.entity.LabNotify;
import org.jeecg.modules.lab.notify.service.ILabNotifyService;
import org.jeecg.modules.lab.sample.entity.LabSampleRecord;
import org.jeecg.modules.lab.sample.record.service.ILabSampleRecordService;
import org.jeecg.modules.lab.util.BeanChangeUtil;
import org.jeecg.modules.lab.util.FlowNumberUtil;
import org.jeecg.modules.lab.util.ReportData;
import org.jeecg.modules.lab.util.ReportLoad;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @Description: 委托信息表
 * @Author: jeecg-boot
 * @Date: 2023-07-17
 * @Version: V1.0
 */
@Api(tags = "委托信息表")
@RestController
@RequestMapping("/entrust/labEntrust")
@Slf4j
public class LabWentrustController {
    @Autowired
    private ILabWsuperviseService labWsuperviseService;
    @Autowired
    private ILabWentrustService labEntrustService;

    @Autowired
    private ILabEntrustSampleService labSampleService;

    @Autowired
    private ILabEntrustItemsService labEntrustItemsService;

    @Autowired
    private ILabSampleRecordService labSampleRecordService;

    @Autowired
    private BeanChangeUtil<LabWentrust> beanChangeUtil;

    @Autowired
    private FlowNumberUtil flowNumberUtil;
    @Autowired
    private ILabWentrustService labWentrustService;
    //原始记录基础信息
    @Autowired
    private ILabItemsRecordSampleService labItemsRecordSampleService;
    //原始记录仪器
    @Autowired
    private ILabItemsRecordDeviceService labItemsRecordDeviceService;
    //原始记录内容
    @Autowired
    private ILabItemsRecordNormService labItemsRecordNormService;
    //原始记录结果
    @Autowired
    private ILabItemsRecordTargetService labItemsRecordTargetService;
    //原始记录检测人
    @Autowired
    private ILabItemsRecordPersonService labItemsRecordPersonService;
    //实验报告单
    @Autowired
    private ILabItemsRecordReportService labItemsRecordReportService;

    @Autowired
    private ILabCronJobService labCronJobService;

    @Autowired
    private ILabNotifyService labNotifyService;
    @Autowired
    private ILabEntrustItemsIndexService labEntrustItemsIndexService;

    @Autowired
    private ILabTaskAllotService labTaskAllotService;


    /**
     * 分页列表查询
     *
     * @param labEntrust
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "委托信息表-分页列表查询", notes = "委托信息表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<LabWentrust>> queryPageList(LabWentrust labEntrust,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<LabWentrust> queryWrapper = new QueryWrapper<>();
        if (labEntrust.getEntName() != null) {
            String entName = labEntrust.getEntName();
            String replace = entName.replace("*", "");
            queryWrapper.like("ent_name", "%" + replace + "%");
        }
        if (labEntrust.getHandler() != null) {
            String entName = labEntrust.getHandler();
            String replace = entName.replace("*", "");
            queryWrapper.like("handler", "%" + replace + "%");
        }
        if (labEntrust.getSampleType() != null) {
            String entName = labEntrust.getSampleType();
            String replace = entName.replace("*", "");
            queryWrapper.like("sample_type_id", "%" + replace + "%");
        }
        if (labEntrust.getHandlDate() != null) {
            String entName = labEntrust.getHandlDate();
            String replace = entName.replace("*", "");
            queryWrapper.like("handl_date", "%" + replace + "%");
        }
        queryWrapper.orderByDesc("create_time");
        Page<LabWentrust> page = new Page<LabWentrust>(pageNo, pageSize);
        IPage<LabWentrust> pageList = labEntrustService.page(page, queryWrapper);
        return Result.OK(pageList);
    }


    @ApiOperation(value = "委托信息表-初审、复审列表查询", notes = "委托信息表-初审、复审列表查询")
    @GetMapping(value = "/auditList")
    public Result<IPage<LabWentrust>> queryAuditList(LabWentrust labEntrust,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "50") Integer pageSize,
                                                     @RequestParam(name = "auditMark", defaultValue = "") String auditMark,
                                                     @RequestParam(name = "entName", defaultValue = "") String entName,
                                                     @RequestParam(name = "handler", defaultValue = "") String handler,
                                                     @RequestParam(name = "sampleType", defaultValue = "") String sampleType) {

        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = loginUser.getId();
        String userName = loginUser.getRealname();
        List<LabWentrust> pageList = labEntrustService.getAuditList(auditMark, entName.replace("*", ""), handler.replace("*", ""), labEntrust.getHandlDate(), sampleType, userId, userName);
        IPage<LabWentrust> page = new Page<>(pageNo, pageSize);
        page.setRecords(pageList);
        page.setTotal(pageList.size());
        return Result.OK(page);
    }


    /**
     * 分页列表查询
     *
     * @param labEntrust
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "委托信息表-合同归档", notes = "委托信息表-合同归档")
    @GetMapping(value = "/conlist")
    public Result<IPage<LabWentrust>> queryConPageList(LabWentrust labEntrust,
                                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                       HttpServletRequest req) {
        QueryWrapper<LabWentrust> queryWrapper = QueryGenerator.initQueryWrapper(labEntrust, req.getParameterMap());
        queryWrapper.isNotNull("con_atta").ne("con_atta", "");
        queryWrapper.orderByDesc("create_time");
        Page<LabWentrust> page = new Page<LabWentrust>(pageNo, pageSize);
        IPage<LabWentrust> pageList = labEntrustService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param labEntrustPage
     * @return
     */
    @AutoLog(value = "委托信息表-添加")
    @ApiOperation(value = "委托信息表-添加", notes = "委托信息表-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody LabEntrustPage labEntrustPage) {
        LabWentrust labEntrust = new LabWentrust();
        BeanUtils.copyProperties(labEntrustPage, labEntrust);
        labEntrust.setSampleCount(labEntrustPage.getLabSampleList().size());
        labEntrustService.saveMain(labEntrust, labEntrustPage.getLabSampleList());

        if (MyEnum.sync) {
            //同步表信息
            long time = new Date().getTime();
            List<LabCronJob> jobs = new ArrayList<>();
            jobs.add(new LabCronJob("lab_wentrust", "0", time, 1));
            jobs.add(new LabCronJob("lab_entrust_sample", "0", time, 2));
            labCronJobService.saveBatch(jobs);
        }

        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param labEntrustPage
     * @return
     */
    @AutoLog(value = "委托信息表-编辑")
    @ApiOperation(value = "委托信息表-编辑", notes = "委托信息表-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody LabEntrustPage labEntrustPage) throws Exception {
        LabWentrust labEntrust = new LabWentrust();
        BeanUtils.copyProperties(labEntrustPage, labEntrust);
        LabWentrust labEntrustEntity = labEntrustService.getById(labEntrust.getId());
        if (labEntrustEntity == null) {
            return Result.error("未找到对应数据");
        }

        labEntrust.setSampleCount(labEntrustPage.getLabSampleList().size());
        labEntrustService.updateMain(labEntrust, labEntrustPage.getLabSampleList());

        if (MyEnum.sync) {
            long time = new Date().getTime();
            List<LabCronJob> jobs = new ArrayList<>();
            String condition = " entrust_id = '" + labEntrust.getId() + "'";
            jobs.add(new LabCronJob("lab_wentrust", "1", time, 1));
            jobs.add(new LabCronJob("lab_entrust_sample", "2", condition, time, 2));
            jobs.add(new LabCronJob("lab_entrust_sample", "1", time, 3));
            labCronJobService.saveBatch(jobs);
        }
        return Result.OK("编辑成功!");
    }

    /**
     * 获取样品编号
     *
     * @param rule
     * @param num
     * @return
     */
    @ApiOperation(value = "样品信息-生成样品编号", notes = "样品信息-生成样品编号")
    @GetMapping(value = "/SamCodeSerialNum")
    public Result<List<String>> SamCodeSerialNum(@RequestParam(name = "rule", defaultValue = "") String rule,
                                                 @RequestParam(name = "num", defaultValue = "0") Integer num) {
        List<String> list = flowNumberUtil.generateSerialNum(rule, num);
        return Result.OK(list);
    }


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "委托信息表-通过id删除")
    @ApiOperation(value = "委托信息表-通过id删除", notes = "委托信息表-通过id删除")
//    @RequiresPermissions("entrust:lab_entrust:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        labEntrustService.delMain(id);

        if (MyEnum.sync) {
            //删除条件
            String condition1 = "id='" + id + "'";
            String condition2 = "entrust_id = '" + id + "'";
            //同步表信息
            long time = new Date().getTime();
            ArrayList<LabCronJob> jobs = new ArrayList<>();
            jobs.add(new LabCronJob("lab_wentrust", "2", condition1, time, 1));
            jobs.add(new LabCronJob("lab_entrust_sample", "2", condition2, time, 2));
            labCronJobService.saveBatch(jobs);
        }
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "委托信息表-批量删除")
    @ApiOperation(value = "委托信息表-批量删除", notes = "委托信息表-批量删除")
//    @RequiresPermissions("entrust:lab_entrust:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        labEntrustService.delBatchMain(Arrays.asList(ids.split(",")));

        if (MyEnum.sync) {
            long time = new Date().getTime();
            String[] idList = ids.split(",");
            labCronJobService.saveCronBatch("lab_device", "2", time, idList);
        }
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "委托信息表-通过id查询", notes = "委托信息表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<LabWentrust> queryById(@RequestParam(name = "id", required = true) String id) {
        LabWentrust labEntrust = labEntrustService.getById(id);
        if (labEntrust == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(labEntrust);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "查询样品信息-通过主表ID查询", notes = "查询样品信息-通过主表ID查询")
    @GetMapping(value = "/queryLabSampleByMainId")
    public Result<IPage<LabEntrustSample>> queryLabSampleListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<LabEntrustSample> labSampleList = labSampleService.selectByMainId(id);
        IPage<LabEntrustSample> page = new Page<>();
        page.setRecords(labSampleList);
        page.setTotal(labSampleList.size());
        return Result.OK(page);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "查询项目信息-通过主表ID查询", notes = "查询项目信息-通过主表ID查询")
    @GetMapping(value = "/queryLabItemsByMainId")
    public Result<IPage<LabEntrustItems>> queryLabItemsListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<LabEntrustItems> labEntrustItems = labEntrustItemsService.selectItemsByMainId(id);
        IPage<LabEntrustItems> page = new Page<>();
        page.setRecords(labEntrustItems);
        page.setTotal(labEntrustItems.size());
        return Result.OK(page);
    }

    /**
     * 通过委托单id查询样品信息
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "样品信息表-通过委托单id查询", notes = "样品信息表-通过委托单id查询")
    @GetMapping(value = "/queryLabSampleListByEntId")
    public Result<?> queryOrderCustomerListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<LabEntrustSample> labSampleList = labSampleService.selectByMainId(id);
        return Result.ok(labSampleList);
    }

    /**
     * 提交委托至初审/复审
     *
     * @param id
     * @return
     */
    @AutoLog(value = "委托信息表-提交委托至初审/复审")
    @ApiOperation(value = "委托信息表-提交委托至初审/复审", notes = "委托信息表-提交委托至初审/复审")
    @DeleteMapping(value = "/submitFirstEnt")
    public Result<String> submitFirstEnt(@RequestParam(name = "id", required = true) String id, @RequestParam(name = "auditMark", required = true) String auditMark) throws NoSuchAlgorithmException, IOException, InvalidKeyException {


        List<LabAdutiUserPage> labAdutiUsers = labTaskAllotService.queryAduitUsers(id);
        String nameStr = "";
        if (labAdutiUsers != null) {
            for (LabAdutiUserPage user : labAdutiUsers) {
                if ("".equals(nameStr)) {
                    nameStr = user.getUName();
                } else {
                    nameStr = nameStr + "," + user.getUName();
                }
            }
        }
        labEntrustService.updateEntStatusById(id, auditMark, nameStr);


        for (int i = 0; i < labAdutiUsers.size(); i++) {
            LabAdutiUserPage userPage = labAdutiUsers.get(0);

            LabNotify labNotify = new LabNotify();
            labNotify.setNotName("委托检测审核");
            labNotify.setItemName("");
            labNotify.setNotTitlle("委托");
            //todo:确认taskid是项目的id
            labNotify.setTaskId(userPage.getTId());
            String taskName = "您有一条委托检测单待审核，请尽快前往[实验室系统]进行办理！";
            labNotify.setTaskName(taskName);
            labNotify.setEntrustId(userPage.getTId());
            labNotify.setUserId(userPage.getUtId());
            labNotify.setNotStatus("未读");
            labNotify.setFinish(0);
            labNotify.setPubTime(new Date());
            labNotifyService.save(labNotify);

            String tId = userPage.getUtId();
            if (!"".equals(tId) && tId != null) {
                TokenServess tokenServess = new TokenServess();
                String tokenServe = tokenServess.getTokenServe();
                tokenServess.getSysmw(taskName, tId, tokenServe);
            }
        }

        if (MyEnum.sync) {
            long time = new Date().getTime();
            List<LabCronJob> jobs = new ArrayList<>();
            jobs.add(new LabCronJob("lab_notify", "0", time, 1));
            jobs.add(new LabCronJob("lab_wentrust", "0", time, 2));
            labCronJobService.saveBatch(jobs);
        }

        return Result.OK("提交成功！");
    }

    /**
     * 委托单初审/复审通过
     *
     * @param labEntrustPage
     * @return
     */
    @AutoLog(value = "委托信息表-委托单初审/审核通过")
    @ApiOperation(value = "委托信息表-委托单初审/审核通过", notes = "委托信息表-委托单初审/审核通过")
    @RequestMapping(value = "/auditPass", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> auditPass(@RequestBody LabEntrustPage labEntrustPage) throws Exception {
        //获取登录人员
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LabWentrust labEntrust = new LabWentrust();
        BeanUtils.copyProperties(labEntrustPage, labEntrust);
        LabWentrust labEntrustEntity = labEntrustService.getById(labEntrust.getId());
        if (labEntrustEntity == null) {
            return Result.error("未找到对应数据");
        }
        //添加初审人/复审人id
        if (labEntrust.getAuditMark().equals("初审通过")) {
            labEntrust.setFirstAuditId(loginUser.getId());
        } else if (labEntrust.getAuditMark().equals("审核通过")) {
            labEntrust.setFinalAuditId(loginUser.getId());
        }
        //用户操作描述
        String operateMark = labEntrustPage.getOperateMark();
        //记录初审/复审时单据修改前后数据
        beanChangeUtil.saveOperation(loginUser, labEntrustEntity, labEntrust, labEntrust.getId(), "labEntrust", operateMark);
        //保存委托信息
        labEntrustService.updateMain(labEntrust, labEntrustPage.getLabSampleList());
        //插入样品流转记录
        if (labEntrust.getAuditMark().equals("审核通过")) {
            //todo  龙芋西当前是固定的  后续要增加字段调整
            labSampleRecordService.addRecords(labEntrustPage.getLabSampleList(), "入库", "龙芋西");
        }
        if (MyEnum.sync) {
            //同步表信息
            long time = new Date().getTime();
            ArrayList<LabCronJob> jobs = new ArrayList<>();
            String condition = " entrust_id = '" + labEntrust.getId() + "'";
            jobs.add(new LabCronJob("lab_wentrust", "1", time, 1));
            jobs.add(new LabCronJob("lab_entrust_sample", "2", condition, time, 2));
            jobs.add(new LabCronJob("lab_entrust_sample", "1", time, 3));
            if (labEntrust.getAuditMark().equals("审核通过")) {
                jobs.add(new LabCronJob("lab_entrust_items", "0", time, 4));
                jobs.add(new LabCronJob("lab_entrust_items_index", "0", time, 5));
                jobs.add(new LabCronJob("lab_items_record_sample", "0", time, 6));
                jobs.add(new LabCronJob("lab_items_record_norm", "0", time, 7));
                jobs.add(new LabCronJob("lab_items_record_target", "0", time, 8));
                jobs.add(new LabCronJob("lab_items_record_person", "0", time, 9));
                jobs.add(new LabCronJob("lab_sample_record", "0", time, 10));
                jobs.add(new LabCronJob("lab_items_record_device", "0", time, 11));
            }
            labCronJobService.saveBatch(jobs);
        }
        return Result.OK(labEntrust.getAuditMark());
    }

    /**
     * 委托单初审/复审退回
     *
     * @param labEntrustPage
     * @return
     */
    @AutoLog(value = "委托信息表-委托单初审/复审退回")
    @ApiOperation(value = "委托信息表-委托单初审/复审退回", notes = "委托信息表-委托单初审/复审退回")
    @RequestMapping(value = "/auditBack", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> auditBack(@RequestBody LabEntrustPage labEntrustPage) throws Exception {
        LabWentrust labEntrust = new LabWentrust();
        BeanUtils.copyProperties(labEntrustPage, labEntrust);
        LabWentrust labEntrustEntity = labEntrustService.getById(labEntrust.getId());
        if (labEntrustEntity == null) {
            return Result.error("未找到对应数据");
        }
        //用户操作描述
        String operateMark = labEntrustPage.getOperateMark();
        //获取登录人员
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //记录初审/复审退回时单据修改前后数据
        beanChangeUtil.saveOperation(loginUser, labEntrustEntity, labEntrust, labEntrust.getId(), "labEntrust", operateMark);
        labEntrustService.updateMain(labEntrust, labEntrustPage.getLabSampleList());

        if (MyEnum.sync) {
            //同步表信息
            long time = new Date().getTime();
            ArrayList<LabCronJob> jobs = new ArrayList<>();
            String condition = " entrust_id = '" + labEntrust.getId() + "'";
            jobs.add(new LabCronJob("lab_wentrust", "1", time, 1));
            jobs.add(new LabCronJob("lab_entrust_sample", "2", condition, time, 2));
            jobs.add(new LabCronJob("lab_entrust_sample", "1", time, 3));
            labCronJobService.saveBatch(jobs);
        }
        return Result.OK("退回成功!");
    }

    /**
     * 委托单撤销
     * 撤销分为：“初审中”撤销回“制单中”，“复审中”撤销回“初审通过”
     *
     * @param id
     * @return
     */
    @AutoLog(value = "委托信息表-委托单撤销")
    @ApiOperation(value = "委托信息表-委托单撤销", notes = "委托信息表-委托单撤销")
    @DeleteMapping(value = "/cancelOneEnt")
    public Result<String> cancelOneEnt(@RequestParam(name = "id", required = true) String id, @RequestParam(name = "auditMark", required = true) String auditMark) {

        labEntrustService.updateEntStatusById(id, auditMark, null);

        if (MyEnum.sync) {
            //同步表信息
            long time = new Date().getTime();
            LabCronJob cronJob = new LabCronJob("lab_wentrust", "1", time, 1);
            labCronJobService.save(cronJob);
        }
        return Result.OK("撤销成功！");
    }

    /**
     * 按月统计当年的委托数量
     *
     * @return
     */
    @ApiOperation(value = "委托信息表-按月统计当年的委托数量", notes = "委托信息表-按月统计当年的委托数量")
    @GetMapping(value = "/queryEntrustY")
    public Result<LabEntrustAnaPageA> queryEntrustY() {
        LabEntrustAnaPageA labEntrusta = labEntrustService.queryEntrustYCount();
        return Result.OK(labEntrusta);

    }

    /**
     * 统计当月委托数量
     *
     * @return
     */
    @ApiOperation(value = "委托信息表-统计当月委托数量", notes = "委托信息表-统计当月委托数量")
    @GetMapping(value = "/queryEntrustM")
    public Result<IPage<LabEntrustAnaPageB>> queryEntrustM() {
        List<LabEntrustAnaPageB> labEntrustb = labEntrustService.queryEntrustMCount();
        IPage<LabEntrustAnaPageB> page = new Page<>();
        page.setRecords(labEntrustb);
        page.setTotal(labEntrustb.size());
        return Result.OK(page);

    }

    /**
     * 根据t_id查询用户id
     *
     * @return
     */
    @ApiOperation(value = "根据t_id查询用户id", notes = "根据t_id查询用户id")
    @GetMapping(value = "/byTidList")
    public Result<String> byTidList(String tId) {
        String[] split = tId.split(",");
        String userIds = "";
        for (String s : split) {
            LoginUser loginUser = labEntrustService.byLoginUser(Integer.parseInt(s));
            if (userIds == "") {
                userIds = loginUser.getId();
            } else {
                userIds = userIds + "," + loginUser.getId();
            }
        }
        return Result.OK(userIds);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param labEntrust
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, LabWentrust labEntrust) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<LabWentrust> queryWrapper = QueryGenerator.initQueryWrapper(labEntrust, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Date day = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //配置选中数据查询条件
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id", selectionList);
        }
        //Step.2 获取导出数据
        List<LabWentrust> labEntrustList = labEntrustService.list(queryWrapper);

        // Step.3 组装pageList
        List<LabEntrustPage> pageList = new ArrayList<LabEntrustPage>();
        for (LabWentrust main : labEntrustList) {
            LabEntrustPage vo = new LabEntrustPage();
            BeanUtils.copyProperties(main, vo);
            List<LabEntrustSample> LabSamplelist = labSampleService.selectByMainId(main.getId());
            vo.setLabSampleList(LabSamplelist);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "委托信息");
        mv.addObject(NormalExcelConstants.CLASS, LabEntrustPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("委托信息数据", "导出人:" + sysUser.getRealname() + "         导出时间:" + sdf.format(day), "委托信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        int num = 0;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<LabEntrustPage> list = ExcelImportUtil.importExcel(file.getInputStream(), LabEntrustPage.class, params);
                for (LabEntrustPage page : list) {
                    LabWentrust po = new LabWentrust();
                    String entName = page.getEntName();
                    if (!"".equals(entName) && entName != null && !entName.contains("必填")) {
                        BeanUtils.copyProperties(page, po);
                        handleImportDat(po, page.getLabSampleList());
                        labEntrustService.importSaveMain(po, page.getLabSampleList());
                        num++;
                    }
                }
                if (MyEnum.sync) {
                    long time = new Date().getTime();
                    List<LabCronJob> jobs = new ArrayList<>();
                    //默认还没有同步数据
                    jobs.add(new LabCronJob("lab_wentrust", "0", time, 1));
                    jobs.add(new LabCronJob("lab_entrust_sample", "0", time, 2));
                    labCronJobService.saveBatch(jobs);
                }
                return Result.OK("文件导入成功！数据行数:" + num);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

    /**
     * 处理导入的数据
     *
     * @param po
     * @param LabSamplelist
     */
    public void handleImportDat(LabWentrust po, List<LabEntrustSample> LabSamplelist) {
        po.setReviewA("1");
        po.setReviewB("1");
        po.setReviewC("1");
        po.setReviewD("1");
        po.setReviewE("1");
        po.setReviewF("1");
        po.setReviewG("1");
        po.setReviewH("1");
        po.setReviewI("1");
    }


    @ResponseBody
    @RequestMapping("/downloadExcel")
    public void downloadExcel(HttpServletResponse response, HttpServletRequest request) {
        //方法一：直接下载路径下的文件模板（这种方式貌似在SpringCloud和SpringBoot中，打包成jar包时，无法读取到指定路径下面的文件，不知道记错没，你们可以自己尝试下！！！）
        try {
            //获取要下载的模板名称
            String fileName = "委托信息表.xlsx";
            //设置要下载的文件的名称
            response.setHeader("Content-disposition", "attachment;fileName=" + fileName);
            //通知客服文件的MIME类型
            response.setContentType("application/octet-stream;charset=UTF-8");
            //获取文件的路径
            String filePath = getClass().getResource("D:\\opt\\template\\" + fileName).getPath();
            FileInputStream input = new FileInputStream(filePath);
            OutputStream out = response.getOutputStream();
            byte[] b = new byte[2048];
            int len;
            while ((len = input.read(b)) != -1) {
                out.write(b, 0, len);
            }
            response.setHeader("Content-Length", String.valueOf(input.getChannel().size()));
            input.close();
//            return response.ok("应用导入模板下载完成");
        } catch (Exception ex) {
//            logger.error("getApplicationTemplate :", ex);
            //return Response.ok("应用导入模板下载失败！");
        }
    }

    /**
     * 根据用户id判断是否存在签名
     * userId 用户id
     *
     * @return
     */
    @ApiOperation(value = "根据用户id判断是否存在签名", notes = "根据用户id判断是否存在签名")
    @GetMapping(value = "/byuserIdif")
    public Result<LoginUser> byuserIdif(@RequestParam(value = "userId") String userId) {
        LoginUser oneUser = labEntrustService.getOneUser(userId);
        return Result.OK(oneUser);
    }

    /**
     * 根据用户id获取图片地址
     * userId 用户id
     *
     * @return
     */
    @ApiOperation(value = "根据用户id获取图片地址", notes = "根据用户id获取图片地址")
    @GetMapping(value = "/byIdsa")
    public Result<String> byIdsa(@RequestParam(value = "userId") String userId) {
        LoginUser loginUser = labNotifyService.byIdLogUser(userId);
        int lastIndex = loginUser.getTpicture().lastIndexOf("\\"); // 获取最后一个字符的索引
        String result = "";
        if (lastIndex != -1) {
            result = loginUser.getTpicture().substring(lastIndex + 1);
        } else {
            System.out.println("未在本地找到相关签名");
        }

        String url = "http://10.89.208.24:7010/tempImages/" + result;
        return Result.ok(url);
    }

    /**
     * 去除相同的设备名称
     *
     * @param labEntrustItems
     * @return
     */
    public String deduplication(List<LabEntrustItems> labEntrustItems) {
        String reportingEquipment = "";
        //拿到这个报告里的所有设备
        ArrayList array = new ArrayList();
        for (int i = 0; labEntrustItems.size() > i; i++) {
            String id = labEntrustItems.get(i).getId();
            List<LabItemsRecordDevice> labItemsRecordSampleList = labItemsRecordDeviceService.byEntrustItemId(id);
            if (labItemsRecordSampleList.size() > 0) {
                for (int a = 0; labItemsRecordSampleList.size() > a; a++) {
                    array.add(labItemsRecordSampleList.get(a).getDevName());
                }
            }
        }
        for (int x = 0; x < array.size() - 1; x++) {
            for (int y = x + 1; y < array.size(); y++) {
                if (array.get(x).equals(array.get(y))) {
                    array.remove(y);
                    y--;
                }
            }
        }
        // 遍历集合
        Iterator it = array.iterator();
        while (it.hasNext()) {
            if ("".equals(reportingEquipment)) {
                reportingEquipment = (String) it.next();
            } else {
                reportingEquipment = reportingEquipment + "、" + (String) it.next();
            }
        }
        return reportingEquipment;
    }

    /**
     * 获取报告中去重后的检测人
     *
     * @param maps
     * @param labEntrustItems
     */
    public void allUeitmer(Map maps, List<LabEntrustItems> labEntrustItems) {

        String sas = "";
        ArrayList array = new ArrayList();
        for (int i = 0; i < labEntrustItems.size(); i++) {
            array.add(labEntrustItems.get(i).getUserName());
        }
        for (int x = 0; x < array.size() - 1; x++) {
            for (int y = x + 1; y < array.size(); y++) {
                if (array.get(x).equals(array.get(y))) {
                    array.remove(y);
                    y--;
                }
            }
        }
        // 遍历集合
        Iterator it = array.iterator();
        while (it.hasNext()) {
            sas += (String) it.next() + ";";
        }
        maps.put("allUeitmer", sas);
    }


    /**
     * 拿主检人，审核人，批准人的签名
     *
     * @param labItemsRecordReport
     * @return
     */
    public Map<String, String> signatureHashMap(LabItemsRecordReport labItemsRecordReport) {
        HashMap<String, String> signatureHashMap = new HashMap<>();
        //图片位置
        String path = "D:\\zhuiExperiment\\picture\\";
        LoginUser checkId = labEntrustService.getOneUser(labItemsRecordReport.getCheckId());
        if (checkId != null) {
            signatureHashMap.put("editorChiefs2", checkId.getTpicture());
        } else {
            signatureHashMap.put("editorChiefs2", path + "签名.jpg");
        }
        LoginUser auditId = labEntrustService.getOneUser(labItemsRecordReport.getAuditId());
        if (auditId != null) {
            signatureHashMap.put("firstAudits1", checkId.getTpicture());
        } else {
            signatureHashMap.put("firstAudits1", path + "签名.jpg");
        }
        LoginUser ratifyId = labEntrustService.getOneUser(labItemsRecordReport.getRatifyId());
        if (ratifyId != null) {
            signatureHashMap.put("finalAudits1", checkId.getTpicture());
        } else {
            signatureHashMap.put("finalAudits1", path + "签名.jpg");
        }
        return signatureHashMap;
    }

    /**
     * 封装结果单需要的数据
     */
    public void rets(Map maps, String id) {
        List<LabEntrustItemsIndexPage> labEntrustItemsIndexList = labEntrustItemsIndexService.getItemsIndexByTaskId(id);
        ArrayList<LabEntrustItemsIndexPage> mapss = new ArrayList<>();
        for (LabEntrustItemsIndexPage labEntrustItemsIndexPage : labEntrustItemsIndexList) {
            if (labEntrustItemsIndexPage.getIndexName() == null) {
                labEntrustItemsIndexPage.setIndexName("");
            }
            if (labEntrustItemsIndexPage.getIndexBasis() == null) {
                labEntrustItemsIndexPage.setIndexBasis("");
            } else {
                String s = labEntrustItemsIndexPage.getIndexBasis().replaceAll("<", "＜")
                        .replaceAll(">", "＞");
                labEntrustItemsIndexPage.setIndexBasis(s);
            }
            if (labEntrustItemsIndexPage.getItemResult() == null) {
                labEntrustItemsIndexPage.setItemResult("");
            }
            if (labEntrustItemsIndexPage.getItemDecide() == null) {
                labEntrustItemsIndexPage.setItemDecide("");
            }
            if (labEntrustItemsIndexPage.getBasisNum() == null) {
                labEntrustItemsIndexPage.setBasisNum("");
            }
            mapss.add(labEntrustItemsIndexPage);
        }
        LabEntrustItemsIndexPage labEntrustItemsIndexPage = new LabEntrustItemsIndexPage();
        labEntrustItemsIndexPage.setItemsBasisName("以下无正文");
        labEntrustItemsIndexPage.setIndexName("");
        labEntrustItemsIndexPage.setIndexBasis("");
        labEntrustItemsIndexPage.setItemResult("");
        labEntrustItemsIndexPage.setItemDecide("");
        labEntrustItemsIndexPage.setBasisNum("");
        mapss.add(labEntrustItemsIndexPage);

        int num = labEntrustItemsIndexList.size();
        for (int i = 0; i < 12 - num - 1; i++) {
            LabEntrustItemsIndexPage labEntrustItemsIndex = new LabEntrustItemsIndexPage();
            labEntrustItemsIndex.setItemsBasisName("");
            labEntrustItemsIndex.setIndexName("");
            labEntrustItemsIndex.setIndexBasis("");
            labEntrustItemsIndex.setItemResult("");
            labEntrustItemsIndex.setItemDecide("");
            labEntrustItemsIndex.setBasisNum("");
            mapss.add(labEntrustItemsIndex);
        }
        maps.put("resultDatass", mapss);

    }


    @PostMapping(value = "/downloadReportWord")
    public void downloadReportWord(@PathVariable(value = "id") String id,
                                   @PathVariable(value = "params") String params,
                                   HttpServletResponse httpServletResponse) throws IOException, ParseException, TemplateException, IllegalAccessException {

        //todo 1、查询实验报告单
        QueryWrapper<LabItemsRecordReport> reportWrapper = new QueryWrapper<>();
        reportWrapper.eq("task_id", id);
        LabItemsRecordReport recordReport = labItemsRecordReportService.getOne(reportWrapper);
        //todo 2、样品信息
        QueryWrapper<LabEntrustSample> sampleWrapper = new QueryWrapper<>();
        sampleWrapper.eq("entrust_id", id);
        //todo 2.1、样品信息（主剂、辅剂）
        List<LabEntrustSample> samlist = labSampleService.list(sampleWrapper);
        sampleWrapper.eq("sam_type", "主剂");
        //todo 2.2、样品信息（主剂）
        List<LabEntrustSample> list = labSampleService.list(sampleWrapper);
        LabEntrustSample sample = list.get(0);
        //todo 3、实验项目列表
        List<LabEntrustItems> labEntrustItems = labEntrustItemsService.selectItemsByMainId(id);
        //todo 4、实验全部设备
        String devStr = deduplication(labEntrustItems);
        //todo 5、人员签名图片
        Map rMap = signatureHashMap(recordReport);
        Map map = new HashMap();
        ReportData reportLoad = new ReportData();
        String reportNumber = recordReport.getReportNum();
        String samNum = labEntrustItems.get(0).getSamNum();
        if (params.equals("委托检验")) {
            LabWentrust labWentrust = labWentrustService.getById(id);
            map = reportLoad.getMap(labWentrust, params, rMap, recordReport, labEntrustItems, sample);
        } else {
            LabWsupervise LabWsupervise = labWsuperviseService.getById(id);
            map = reportLoad.getMap(LabWsupervise, params, rMap, recordReport, labEntrustItems, sample);
            map.put("supervise", "supervise.xml");
        }
        //todo 样品登记列表
        map.put("samlist", samlist);
        map.put("report_result", "report_result.xml");
        map.put("report_list", "report_list.xml");
        map.put("sample_list", "sample_list.xml");
        //todo 文件名称
        String path = (String) map.get("path");
        String report_result = (String) map.get("report_result");
        String report_list = (String) map.get("report_list");
        String sample_list = (String) map.get("sample_list");
        //todo 所有的数据项
        Map maps = (Map) map.get("data");
        maps.put("testUsers", labTaskAllotService.getAllTestUsers(id));
        maps.put("testDepart", labTaskAllotService.getTestDepart(id));
        //todo 实验项目检测指标
        rets(maps, id);
        //todo 流转单情况
        sampleStreamtData(maps, id);
        maps.put("reportingEquipment", devStr);
        //todo 获取所有的检查人员
        allUeitmer(maps, labEntrustItems);
        //todo 去null操作
        replaceNull(maps);
        String folderPath = "D:\\zhuiExperiment\\template"; // 模板路径
        folders(folderPath);
        String folderPath22 = "D:\\opt\\upFiles\\labPdf\\" + samNum; // 文件夹路径
        folders(folderPath22);

        //todo 先生成为doc文件   存放文件模板的位置\文件名称\存放文件的路径\数据
        parse(folderPath, path, folderPath22 + "\\" + reportNumber + ".docx", maps);

        parse(folderPath, report_result, folderPath22 + "\\" + reportNumber + "_result.docx", maps);
        parse(folderPath, report_list, folderPath22 + "\\" + reportNumber + "_list.docx", maps);
        if (params.equals("监督检验")) {
            String supervise = (String) map.get("supervise");
            parse(folderPath, supervise, folderPath22 + "\\" + reportNumber + "_supervise.docx", maps);
        }
        parse(folderPath, sample_list, folderPath22 + "\\" + reportNumber + "_samplelist.docx", maps);

        //todo 项目模板
//        if (labEntrustItems != null) {
//            for (int i = 0; i < labEntrustItems.size(); i++) {
//                LabEntrustItems item = labEntrustItems.get(i);
//                String itemName = item.getItemName();
//                if (item.getItemName().contains("/")) {
//                    itemName = item.getItemName().replace("/", "-");
//                }
//                String task_item_id = item.getId();
//                //todo 添加原始记录附件到下面 先生成为doc文件 原始记录第一部分
//                Map mapData = ronrew(itemName, task_item_id);
//                //todo 填充数据
//                Map itemData = (Map) mapData.get("data");
//                //todo 去null操作
//                replaceNull(itemData);
//                String itmePath = itemName + ".xml";
//                parse(folderPath, itmePath, folderPath22 + "\\" + itemName + ".docx", itemData);
//
//            }
//        }
        hcPdfReport(id, params);
    }


    /**
     * 报告提交、审核、审批时从新生成pdf
     *
     * @param id
     * @param params
     * @throws IOException
     * @throws TemplateException
     */
    public void scReportPdf(@PathVariable(value = "id") String id, @PathVariable(value = "params") String params) throws IOException, TemplateException {

        //todo 1、查询实验报告单
        QueryWrapper<LabItemsRecordReport> reportWrapper = new QueryWrapper<>();
        reportWrapper.eq("task_id", id);
        LabItemsRecordReport recordReport = labItemsRecordReportService.getOne(reportWrapper);
        //todo 2、样品信息
        QueryWrapper<LabEntrustSample> sampleWrapper = new QueryWrapper<>();
        sampleWrapper.eq("entrust_id", id);
        //todo 2.1、样品信息（主剂、辅剂）
        List<LabEntrustSample> samlist = labSampleService.list(sampleWrapper);
        sampleWrapper.eq("sam_type", "主剂");
        //todo 2.2、样品信息（主剂）
        List<LabEntrustSample> list = labSampleService.list(sampleWrapper);
        LabEntrustSample sample = list.get(0);
        //todo 3、实验项目列表
        List<LabEntrustItems> labEntrustItems = labEntrustItemsService.selectItemsByMainId(id);
        //todo 4、实验全部设备
        String devStr = deduplication(labEntrustItems);
        //todo 5、人员签名图片
        Map rMap = signatureHashMap(recordReport);
        Map map = new HashMap();
        ReportData reportLoad = new ReportData();
        String reportNumber = recordReport.getReportNum();
        if (params.equals("委托检验")) {
            LabWentrust labWentrust = labWentrustService.getById(id);
            map = reportLoad.getMap(labWentrust, params, rMap, recordReport, labEntrustItems, sample);
        } else {
            LabWsupervise LabWsupervise = labWsuperviseService.getById(id);
            map = reportLoad.getMap(LabWsupervise, params, rMap, recordReport, labEntrustItems, sample);
            map.put("supervise", "supervise.xml");
        }
        map.put("report_result", "report_result.xml");
        //todo 文件名称
        String report_result = (String) map.get("report_result");
        //todo 所有的数据项
        Map maps = (Map) map.get("data");
        maps.put("reportingEquipment", devStr);

        //todo 获取所有的检查人员
        allUeitmer(maps, labEntrustItems);
        //todo 去null操作
        replaceNull(maps);

        //todo 查询实验报告单
        QueryWrapper<LabItemsRecordReport> reportWrapperA = new QueryWrapper<>();
        reportWrapperA.eq("task_id", id);
        LabItemsRecordReport labItemsRecordReport = labItemsRecordReportService.getOne(reportWrapperA);
        String samName = labItemsRecordReport.getSamName();
        String samNum = labItemsRecordReport.getSamNum();

        String folderPath = "D:\\zhuiExperiment\\template"; // 模板路径
        folders(folderPath);
        String folderPath22 = MyEnum.downPdfPath + "\\" + samNum; // 文件夹路径
        folders(folderPath22);

        String reportFile = folderPath22 + "\\" + reportNumber + "_result.docx";

        //todo 删除word
        File rfile = new File(reportFile);
        rfile.delete();
        //todo 重新生成word
        parse(folderPath, report_result, folderPath22 + "\\" + reportNumber + "_result.docx", maps);

        String pdfFileA = folderPath22 + "\\" + params + "-" + reportNumber + "_result.pdf";
        //todo 删除pdf
        File pfile = new File(pdfFileA);
        pfile.delete();
        //todo 重新生成pdf
        wordToPdf(reportFile, pdfFileA);

        String downPath = MyEnum.downPdfPath + "\\" + samNum;
        List<String> fileList = new ArrayList<>();
        //todo 1、报告-首页
        String pdfFile1 = downPath + "\\" + params + "-" + reportNumber + ".pdf";
        fileList.add(pdfFile1);
        //todo 2、报告-次页
        String pdfFile2 = downPath + "\\" + params + "-" + reportNumber + "_result.pdf";
        fileList.add(pdfFile2);
        //todo 3、报告-报告结果
        String pdfFile3 = downPath + "\\" + params + "-" + reportNumber + "_list.pdf";
        fileList.add(pdfFile3);
        //todo 4、委托或监督
        if (params.equals("监督检验")) {
            String pdfFile5 = downPath + "\\" + params + "-" + reportNumber + "_supervise.pdf";
            fileList.add(pdfFile5);
        }
        //todo 5、报告-样品
        String pdfFile4 = downPath + "\\" + params + "-" + reportNumber + "_samplelist.pdf";
        fileList.add(pdfFile4);
        //todo 6、实验项目列表
        if (labEntrustItems != null) {
            for (LabEntrustItems item : labEntrustItems) {
                String itemName = item.getItemName();
                if (item.getItemName().contains("/")) {
                    itemName = item.getItemName().replace("/", "-");
                }
                String pdfFile5 = downPath + "\\" + itemName + ".pdf";
                fileList.add(pdfFile5);

            }
        }
        //todo 合成pdf
        hcPdf(fileList, params, reportNumber, samName, samNum);

    }


    /**
     * 样品流转记录
     *
     * @param maps
     * @param id
     */
    public void sampleStreamtData(Map maps, String id) {
        QueryWrapper<LabSampleRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("bus_id", id);
        queryWrapper.isNotNull("item_name");
        List<LabSampleRecord> labSampleRecords = labSampleRecordService.list(queryWrapper);
        List<LabSampleRecordPage> recordPages = new ArrayList<>();
        for (LabSampleRecord sampleRecord : labSampleRecords) {
            LabSampleRecordPage sampleRecordPage = new LabSampleRecordPage();
            sampleRecordPage.setItemName(sampleRecord.getItemName());
            sampleRecordPage.setSamName(sampleRecord.getSamName());
            sampleRecordPage.setSendPerson(sampleRecord.getOperatePerson());
            sampleRecordPage.setReceivePerson(sampleRecord.getReceivePerson());
            sampleRecordPage.setRecordTime(DateUtils.date2Str(sampleRecord.getRecordTime(), new SimpleDateFormat("yyyy-MM-dd HH:mm")));
            String quantity = String.valueOf(sampleRecord.getSamQuantity());
            if (quantity != null) {
                sampleRecordPage.setSamQuantity(quantity == null ? "0.00" : quantity);
            } else {
                sampleRecordPage.setSamQuantity("--");
            }
            sampleRecordPage.setReceivePerson(sampleRecord.getReceivePerson() == null ? "" : sampleRecord.getReceivePerson());
            recordPages.add(sampleRecordPage);
        }
        maps.put("sampleStreamData", recordPages);

    }


    /**
     * 下载报告
     *
     * @param id
     * @param params
     * @param httpServletResponse
     * @throws Exception
     */
    @PostMapping(value = "/downloadWordA/{id}/{params}")
    public void downloadWordA(@PathVariable(value = "id") String id, @PathVariable(value = "params") String params, HttpServletResponse httpServletResponse) throws Exception {

        //合成pdf
        File file1 = this.hcPdfReport(id, params);
        //往前端传输
        if (httpServletResponse != null) {
            InputStream inputStream = new FileInputStream(file1);
            //再次去读取到本地的pdf文件
            int len;
            byte[] buf = new byte[1024];
            OutputStream stream = httpServletResponse.getOutputStream();
            while ((len = inputStream.read(buf)) != -1) {
                stream.write(buf, 0, len);
            }
            stream.flush();
            inputStream.close();
            stream.close();
            httpServletResponse.setContentType("docx/test.docx; charset=utf-8"); //文本
        }
    }


    /**
     * 下载报告
     */
    @PostMapping(value = "/downloadWord/{id}/{params}")
    public void downloadWord(@PathVariable(value = "id") String id, @PathVariable(value = "params") String params, HttpServletResponse httpServletResponse) throws Exception {


        //查询实验报告单
        QueryWrapper<LabItemsRecordReport> reportWrapper = new QueryWrapper<>();
        reportWrapper.eq("task_id", id);
        LabItemsRecordReport labItemsRecordReport = labItemsRecordReportService.getOne(reportWrapper);
        String reportNumber = labItemsRecordReport.getReportNum();
        String file = "";
        if (params.equals("委托检验")) {
            file = "D:/zhuiExperiment/downloadPath/委托检验-" + reportNumber + ".docx";
        } else {
            file = "D:/zhuiExperiment/downloadPath/监督检验-" + reportNumber + ".docx";
        }
        /*转成pdf*/
        InputStream docxInputStream = null;
        OutputStream outputStream = null;
        try {
            // 原word地址
            docxInputStream = new FileInputStream(file);
            // 转换后pdf生成地址
            outputStream = new FileOutputStream("D:\\zhuiExperiment\\downloadPath\\" + params + "-" + reportNumber + ".pdf");
            IConverter converter = LocalConverter.builder().build();
            converter.convert(docxInputStream)
                    .as(DocumentType.DOCX)
                    .to(outputStream)
                    .as(DocumentType.PDF).execute();
            // 关闭
            converter.shutDown();
            // 关闭
            outputStream.close();
            // 关闭
            docxInputStream.close();
        } catch (Exception e) {
            System.out.println("[documents4J] word转pdf失败:" + e.toString());
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
            if (docxInputStream != null) {
                docxInputStream.close();
            }
        }
        //往前端传输
        if (httpServletResponse != null) {
            File file1 = new File("D:\\zhuiExperiment\\downloadPath\\" + reportNumber + ".pdf");
            InputStream inputStream = new FileInputStream(file1);
            //再次去读取到本地的pdf文件
            int len;
            byte[] buf = new byte[1024];
            OutputStream stream = httpServletResponse.getOutputStream();
            while ((len = inputStream.read(buf)) != -1) {
                stream.write(buf, 0, len);
            }
            stream.flush();
            inputStream.close();
            stream.close();
            httpServletResponse.setContentType("docx/test.docx; charset=utf-8"); //文本
        }
    }

    /**
     * 实验报告合成pdf
     *
     * @param id
     * @param params
     */
    public File hcPdfReport(String id, String params) throws IOException {

        //查询实验报告单
        QueryWrapper<LabItemsRecordReport> reportWrapper = new QueryWrapper<>();
        reportWrapper.eq("task_id", id);
        LabItemsRecordReport labItemsRecordReport = labItemsRecordReportService.getOne(reportWrapper);
        String reportNumber = labItemsRecordReport.getReportNum();
        String samName = labItemsRecordReport.getSamName();
        String samNum = labItemsRecordReport.getSamNum();
        String pdfFile = MyEnum.pdfFile + "/" + samNum;
        String labPath = MyEnum.downPdfPath + "\\" + samNum;
        File pdffile = new File(pdfFile +"/"+ samName + "-" + params + "-" + reportNumber + ".pdf");
        if (!pdffile.exists()) {
            List<String> fileList = new ArrayList<>();
            //todo 1、报告-首页
            String reportFile = labPath + "\\" + reportNumber + ".docx";
            String pdfFile1 = labPath + "\\" + params + "-" + reportNumber + ".pdf";
            wordToPdf(reportFile, pdfFile1);
            fileList.add(pdfFile1);

            //todo 2、报告-次页
            String resultFile = labPath + "\\" + reportNumber + "_result.docx";
            String pdfFile2 = labPath + "\\" + params + "-" + reportNumber + "_result.pdf";
            wordToPdf(resultFile, pdfFile2);
            fileList.add(pdfFile2);

            //todo 3、报告-报告结果
            String listFile = labPath + "\\" + reportNumber + "_list.docx";
            String pdfFile3 = labPath + "\\" + params + "-" + reportNumber + "_list.pdf";
            wordToPdf(listFile, pdfFile3);
            fileList.add(pdfFile3);

            //todo 4、委托或监督
            if (params.equals("监督检验")) {
                String superFile = labPath + "\\" + reportNumber + "_supervise.docx";
                String pdfFile5 = labPath + "\\" + params + "-" + reportNumber + "_supervise.pdf";
                wordToPdf(superFile, pdfFile5);
                fileList.add(pdfFile5);
            }
            //todo 5、报告-样品
            String sampleFile = labPath + "\\" + reportNumber + "_samplelist.docx";
            String pdfFile4 = labPath + "\\" + params + "-" + reportNumber + "_samplelist.pdf";
            wordToPdf(sampleFile, pdfFile4);
            fileList.add(pdfFile4);

            //todo 6、实验项目列表
            List<LabEntrustItems> labEntrustItems = labEntrustItemsService.selectItemsByMainId(id);
            if (labEntrustItems != null) {
                for (LabEntrustItems item : labEntrustItems) {
                    String itemName = item.getItemName();
                    if (item.getItemName().contains("/")) {
                        itemName = item.getItemName().replace("/", "-");
                    }
                    String pdfFile5 = labPath + "\\" + itemName + ".pdf";
                    fileList.add(pdfFile5);
                }
            }
            //todo 合成pdf
            hcPdf(fileList, params, reportNumber, samName, samNum);
        } else {
//            String adocFileA = labPath + "\\" + reportNumber + ".docx";
//            File afileA = new File(adocFileA);
//            afileA.delete();
//            String apdfFileA = labPath + "\\" + params + "-" + reportNumber + ".pdf";
//            File afileB = new File(apdfFileA);
//            afileB.delete();


//            String bdocFileA = labPath + "\\" + reportNumber + "_result.docx";
//            File bfileA = new File(bdocFileA);
//            bfileA.delete();
//            String bpdfFileA = labPath + "\\" + params + "-" + reportNumber + "_result.pdf";
//            File bfileB = new File(bpdfFileA);
//            bfileB.delete();


//            String cdocFileA = labPath + "\\" + reportNumber + "_list.docx";
//            File cfileA = new File(cdocFileA);
//            cfileA.delete();
//            String cpdfFileA = labPath + "\\" + params + "-" + reportNumber + "_list.pdf";
//            File cfileB = new File(cpdfFileA);
//            cfileB.delete();

//            if (params.equals("监督检验")) {
//                String ddocFileA = labPath + "\\" + reportNumber + "_supervise.docx";
//                File dfileA = new File(ddocFileA);
//                dfileA.delete();
//                String dpdfFileA = labPath + "\\" + params + "-" + reportNumber + "_supervise.pdf";
//                File dfileB = new File(dpdfFileA);
//                dfileB.delete();
//            }

//            String edocFileA = labPath + "\\" + reportNumber + "_samplelist.docx";
//            File efileA = new File(edocFileA);
//            efileA.delete();
//            String epdfFileA = labPath + "\\" + params + "-" + reportNumber + "_samplelist.pdf";
//            File efileB = new File(epdfFileA);
//            efileB.delete();

//            List<LabEntrustItems> labEntrustItems = labEntrustItemsService.selectItemsByMainId(id);
//            if (labEntrustItems != null) {
//                for (LabEntrustItems item : labEntrustItems) {
//                    String itemName = item.getItemName();
//                    if (item.getItemName().contains("/")) {
//                        itemName = item.getItemName().replace("/", "-");
//                    }
//                    String fdocFileA = labPath + "\\" + itemName + ".docx";
//                    File ffileA = new File(fdocFileA);
//                    ffileA.delete();
//                    String fpdfFileA = labPath + "\\" + itemName + ".pdf";
//                    File ffileB = new File(fpdfFileA);
//                    ffileB.delete();
//                }
//            }

        }
        return pdffile;
    }


    public void wordToPdf(String file, String pdfFile) throws IOException {
        /*转成pdf*/
        InputStream docxInputStream = null;
        OutputStream outputStream = null;
        try {
            // 原word地址
            docxInputStream = new FileInputStream(file);
            outputStream = new FileOutputStream(pdfFile);
            IConverter converter = LocalConverter.builder().build();
            converter.convert(docxInputStream)
                    .as(DocumentType.DOCX)
                    .to(outputStream)
                    .as(DocumentType.PDF).execute();
            // 关闭
            converter.shutDown();
            // 关闭
            outputStream.close();
            // 关闭
            docxInputStream.close();
        } catch (Exception e) {
            System.out.println("[documents4J] word转pdf失败:" + e.toString());
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
            if (docxInputStream != null) {
                docxInputStream.close();
            }
        }
    }

    public void hcPdf(List<String> listFile, String params, String reportNumber, String samName, String samNum) {
        String result = "D:/opt/upFiles/labPdf/" + samNum + "/" + samName + "-" + params + "-" + reportNumber + ".pdf";

        File pdffile = new File(result);
        if (!pdffile.exists()) {
            pdffile.delete();
        }
        PdfDocument pdfDoc = null;
        try {
            pdfDoc = new PdfDocument(new PdfWriter(result));
            for (String file : listFile) {
                PdfDocument sourcePdfDoc = new PdfDocument(new PdfReader(file));
                sourcePdfDoc.copyPagesTo(1, sourcePdfDoc.getNumberOfPages(), pdfDoc);
                sourcePdfDoc.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pdfDoc.close();
        }

    }

    private ArrayList<String> imageAaw(String itemName, String task_item_id) {
        ArrayList<String> strings = new ArrayList<>();
        LabEntrustItems byId = labEntrustItemsService.getById(task_item_id);
        String itemImageList = byId.getItemImageList();
        if (!"".equals(itemImageList) && itemImageList != null) {
            // 使用正则表达式匹配URL
            Pattern pattern = Pattern.compile("url=(.*?\\.png)");
            Matcher matcher = pattern.matcher(itemImageList);
            while (matcher.find()) {
                // 获取匹配的URL
                String url = matcher.group(1);
                // 提取文件名和扩展名
                int lastSlashIndex = url.lastIndexOf("/");
                String fileNameWithExtension = url.substring(lastSlashIndex + 1);
                String extension = fileNameWithExtension.substring(fileNameWithExtension.lastIndexOf(".") + 1);
                if (extension.equals("png")) {
                    strings.add(url);
                }
            }
        }
        return strings;
    }

    /**
     * 下载实验记录
     */
    @PostMapping(value = "/down_load_experiment/{task_item_id}/{itemName}")
    public void downLoadExperiment(@PathVariable(value = "task_item_id") String task_item_id, @PathVariable(value = "itemName") String itemName, HttpServletResponse httpServletResponse) throws Exception {
        String folderPath = "D:\\zhuiExperiment\\template"; // 模板路径
        folders(folderPath);
        String folderPath22 = "D:\\zhuiExperiment\\downloadPath"; // 文件夹路径
        folders(folderPath22);
        // 添加原始记录附件到下面 先生成为doc文件 原始记录第一部分
        Map ronrew = ronrew(itemName, task_item_id);
        //填充数据
        Map coverData = (Map) ronrew.get("data");
        //去null操作
        replaceNull(coverData);
        //数据路径和路径名
        Calendar calendar = Calendar.getInstance();
        long timestamp = calendar.getTimeInMillis();

        String coverName = folderPath22 + "\\" + timestamp + itemName + ".docx";
        //文件名称
        String paths2 = ronrew.get("path").toString();
        parse(folderPath, paths2, coverName, coverData);

        /*转成pdf*/
        InputStream docxInputStream = null;
        OutputStream outputStream = null;
        try {
            // 原word地址
            docxInputStream = new FileInputStream(coverName);
            // 转换后pdf生成地址
            outputStream = new FileOutputStream(folderPath22 + "\\" + timestamp + itemName + ".pdf");
            IConverter converter = LocalConverter.builder().build();
            converter.convert(docxInputStream)
                    .as(DocumentType.DOCX)
                    .to(outputStream)
                    .as(DocumentType.PDF).execute();
            // 关闭
            converter.shutDown();
            // 关闭
            outputStream.close();
            // 关闭
            docxInputStream.close();
        } catch (Exception e) {
            System.out.println("[documents4J] word转pdf失败:" + e.toString());
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
            if (docxInputStream != null) {
                docxInputStream.close();
            }
        }
        //往前端传输
        if (httpServletResponse != null) {
            File file1 = new File(folderPath22 + "\\" + timestamp + itemName + ".pdf");
            InputStream inputStream = new FileInputStream(file1);
            //再次去读取到本地的pdf文件
            int len;
            byte[] buf = new byte[1024];
            OutputStream stream = httpServletResponse.getOutputStream();
            while ((len = inputStream.read(buf)) != -1) {
                stream.write(buf, 0, len);
            }
            stream.flush();
            inputStream.close();
            stream.close();
            httpServletResponse.setContentType("docx/test.docx; charset=utf-8"); //文本
        }
    }

    /**
     * 通过委托id和项目id查询数据
     */
    public Map ronrew(String itemName, String task_item_id) throws ParseException, IOException, IllegalAccessException {
        Map map1 = new HashMap();
        Map maps2 = new HashMap();
        originalRecord(map1, task_item_id, itemName);
        maps2.put("data", map1);

        return maps2;
    }

    /**
     * 原始记录的查询选择
     *
     * @param replacements
     * @param
     * @throws ParseException
     */
    public void originalRecord(Map replacements, String task_item_id, String itemName) throws ParseException, IOException, IllegalAccessException {//检测项目表lab_entrust_items  //

        //todo 样品信息
        QueryWrapper<LabItemsRecordSample> samWrapper = new QueryWrapper<>();
        samWrapper.eq("task_item_id", task_item_id)
                .eq("field_input", "1");
        List<LabItemsRecordSample> labItemsRecordSampleList = labItemsRecordSampleService.list(samWrapper);
        for (LabItemsRecordSample sample : labItemsRecordSampleList) {
            String fileCode = sample.getFieldCode();
            String fileValue = sample.getFieldValue();
            if ("check_time".equals(fileCode) && fileValue != null && fileValue.contains("至")) {
                String[] parts = fileValue.split("至");
                if (parts.length == 2) {
                    String startDate = parts[0].substring(0, 10); // 获取起始日期部分
                    String endDate = parts[1].substring(0, 10); // 获取结束日期部分
                    String outputDateRange = "";
                    if (endDate == null || "".equals(endDate)) {
                        outputDateRange = startDate;
                    } else {
                        outputDateRange = startDate + "至" + endDate;
                    }
                    replacements.put(fileCode, outputDateRange);
                } else {
                    replacements.put(fileCode, fileValue);
                }
            } else {
                replacements.put(fileCode, fileValue);
            }

        }
        //todo 设备信息
        List<LabItemsRecordDevice> labItemsRecordDevicesList = labItemsRecordDeviceService.byEntrustItemId(task_item_id);
        String devName = "";
        for (LabItemsRecordDevice ssa : labItemsRecordDevicesList) {
            if (devName != "") {
                devName += "\n";
            }
            if (ssa.getDevName() != null && ssa.getDevName() != "") {
                devName += ssa.getDevName() + " ";
            }
            if (ssa.getDevNum() != null && ssa.getDevNum() != "") {
                devName += ssa.getDevNum() + " ";
            }
            if (ssa.getDevValidity() != null && ssa.getDevValidity() != "") {
                devName += ssa.getDevValidity();
            }
        }
        replacements.put("dev_name", devName);
        //todo 检测条件
        QueryWrapper<LabItemsRecordNorm> normWrapper = new QueryWrapper<>();
        normWrapper.eq("task_item_id", task_item_id)
                .eq("field_input", "1");
        List<LabItemsRecordNorm> labItemsRecordNormList = labItemsRecordNormService.list(normWrapper);
        for (LabItemsRecordNorm norm : labItemsRecordNormList) {
            replacements.put(norm.getFieldCode(), norm.getFieldValue());
        }

        //todo 第四部分的原始记录结果
        QueryWrapper<LabItemsRecordTarget> targetWrapper = new QueryWrapper<>();
        targetWrapper.eq("task_item_id", task_item_id)
                .eq("field_input", "1");
        List<LabItemsRecordTarget> labItemsRecordTargetList = labItemsRecordTargetService.list(targetWrapper);
        for (LabItemsRecordTarget target : labItemsRecordTargetList) {
            replacements.put(target.getFieldCode(), target.getFieldValue());
        }
        //todo 第五部分的原始记录签名
        QueryWrapper<LabItemsRecordPerson> personWrapper = new QueryWrapper<>();
        personWrapper.eq("task_item_id", task_item_id)
                .eq("field_input", "1");
        List<LabItemsRecordPerson> labItemsRecordPersonList = labItemsRecordPersonService.list(personWrapper);
        for (LabItemsRecordPerson person : labItemsRecordPersonList) {
            String fielCode = person.getFieldCode();
            String s = "";
            if (person.getFieldValue() != null) {
                String[] split = person.getFieldValue().split(",");
                s = split[0];
            } else {
                s = person.getFieldValue();
            }

            if ("check_person".equals(fielCode) || "person_value1".equals(fielCode)) {
                this.electricSign(fielCode, s, replacements);
            } else if ("audit_person".equals(fielCode) || "person_value2".equals(fielCode)) {
                this.electricSign(fielCode, person.getFieldValue(), replacements);
            }
        }

    }

    /**
     * 替换检测人，复核人的签名为电子签名
     *
     * @param fielCode          检测人/复核人
     * @param reviewPersonFiled 签名
     * @param map1              存放数据的
     * @return
     * @throws IOException
     * @throws IllegalAccessException
     */
    public void electricSign(String fielCode, String reviewPersonFiled, Map map1) throws IOException, IllegalAccessException {
        //图片位置
        String path = "D:\\zhuiExperiment\\picture\\";
        /*检测人不为空，则将检测人名字去匹配电子签名*/
//        if (fielCode != null) {
//            List<LoginUser> userList = labEntrustService.getUserList();
//            if ("check_person".equals(fielCode) || "person_value1".equals(fielCode)) {
//                if ("".equals(reviewPersonFiled) || reviewPersonFiled == null) {
//                    String realPath = path + "签名.jpg";
//                    File file = new File(realPath);
//                    FileInputStream fin4 = new FileInputStream(file);
//                    byte[] bytes4 = new byte[fin4.available()];
//                    fin4.read(bytes4);
//                    fin4.close();
//                    BASE64Encoder encoder4 = new BASE64Encoder();
//                    map1.put(fielCode, encoder4.encode(bytes4));
//                } else {
//                    for (int i = 0; i < userList.size(); i++) {
//                        LoginUser user = userList.get(i);
//                        if (user.getRealname().equals(reviewPersonFiled)) {
//                            if (!"".equals(user.getTpicture()) && user.getTpicture() != null) {
//                                String realPath = user.getTpicture();
//                                File file = new File(realPath);
//                                FileInputStream fin4 = new FileInputStream(file);
//                                byte[] bytes4 = new byte[fin4.available()];
//                                fin4.read(bytes4);
//                                fin4.close();
//                                BASE64Encoder encoder4 = new BASE64Encoder();
//                                map1.put(fielCode, encoder4.encode(bytes4));
//                            } else {
//                                String realPath = path + "签名.jpg";
//                                File file = new File(realPath);
//                                FileInputStream fin4 = new FileInputStream(file);
//                                byte[] bytes4 = new byte[fin4.available()];
//                                fin4.read(bytes4);
//                                fin4.close();
//                                BASE64Encoder encoder4 = new BASE64Encoder();
//                                map1.put(fielCode, encoder4.encode(bytes4));
//                            }
//                            break;
//                        }
//                    }
//                }
//            } else if ("audit_person".equals(fielCode) || "person_value2".equals(fielCode)) {
//                if ("".equals(reviewPersonFiled) || reviewPersonFiled == null) {
//                    String realPath = path + "签名.jpg";
//                    File file = new File(realPath);
//                    FileInputStream fin4 = new FileInputStream(file);
//                    byte[] bytes4 = new byte[fin4.available()];
//                    fin4.read(bytes4);
//                    fin4.read(bytes4);
//                    fin4.close();
//                    BASE64Encoder encoder4 = new BASE64Encoder();
//                    map1.put(fielCode, encoder4.encode(bytes4));
//                } else {
//                    for (int i = 0; i < userList.size(); i++) {
//                        if (userList.get(i).getRealname().equals(reviewPersonFiled)) {
//                            if (!"".equals(userList.get(i).getTpicture()) && userList.get(i).getTpicture() != null) {
//                                //String realPath = path+reviewPersonFiled+"签名.jpg";
//                                String realPath = userList.get(i).getTpicture();
//                                File file = new File(realPath);
//                                FileInputStream fin4 = new FileInputStream(file);
//                                byte[] bytes4 = new byte[fin4.available()];
//                                fin4.read(bytes4);
//                                fin4.read(bytes4);
//                                fin4.close();
//                                BASE64Encoder encoder4 = new BASE64Encoder();
//                                map1.put(fielCode, encoder4.encode(bytes4));
//                            } else {
//                                String realPath = path + "签名.jpg";
//                                File file = new File(realPath);
//                                FileInputStream fin4 = new FileInputStream(file);
//                                byte[] bytes4 = new byte[fin4.available()];
//                                fin4.read(bytes4);
//                                fin4.read(bytes4);
//                                fin4.close();
//                                BASE64Encoder encoder4 = new BASE64Encoder();
//                                map1.put(fielCode, encoder4.encode(bytes4));
//                            }
//                            break;
//                        }
//                    }
//                }
//
//            }
//
//        }
    }

    /**
     * 替换NULL为""
     */
    public void replaceNull(Map data) {
        Set keys = data.keySet();
        for (Object key : keys) {
            if (data.get(key) == null) {
                data.put(key, "");
            }
        }
    }

    /**
     * 判断文件是否存在，不存在就创建
     */
    public void folders(String path) {
        File folder = new File(path);
        // 检查文件夹是否存在
        if (!folder.exists()) {
            // 创建文件夹
            boolean created = folder.mkdirs();
            if (created) {
                System.out.println("文件夹创建成功！");
            } else {
                System.out.println("文件夹创建失败！");
            }
        }
    }

    /**
     * 生成word的方法     存放文件模板的位置\文件名称\存放文件的路径\数据
     *
     * @param templateDir  存放文件模板的位置
     * @param templateName 文件名称
     * @param excelPath    存放文件的路径
     * @param data         数据
     * @throws IOException
     * @throws freemarker.template.TemplateException
     */
    public void parse(String templateDir, String templateName, String excelPath, Map<String, Object> data) throws IOException, freemarker.template.TemplateException {
        //初始化工作
        Configuration cfg = new Configuration();
        //设置默认编码格式为UTF-8
        cfg.setDefaultEncoding("gbk");
        //全局数字格式
        cfg.setNumberFormat("0");
        //设置模板文件位置
        cfg.setDirectoryForTemplateLoading(new File(templateDir));
        cfg.setObjectWrapper(new DefaultObjectWrapper());
        //加载模板
        freemarker.template.Template template = cfg.getTemplate(templateName, "utf-8");
        Writer writer = null;
        try {
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(excelPath), "UTF-8"));
            template.process(data, writer);

            writer.flush();
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    /**
     * 签名url地址转存数据库
     */
    @ApiOperation(value = "签名url地址转存数据库", notes = "签名url地址转存数据库")
    @PostMapping(value = "/signature")
    public Result signatures(@RequestParam(value = "id") String id, @RequestParam(value = "paramasa") String paramasa) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ReportLoad reportLoad = new ReportLoad();
        String s = reportLoad.upSignature(user.getRealname(), paramasa);
        //System.out.println("Base64 encoded URL: " + s);
        labWentrustService.updatasz(user.getId(), s);
        return Result.OK("ok");
    }

    /**
     * 获取服务token和员工票据
     *
     * @return
     */
    @ApiOperation(value = "获取servetoken和 employeeTicket", notes = "获取servetoken和 employeeTicket")
    @GetMapping(value = "/serveToken")
    public Map serveToken() throws NoSuchAlgorithmException, IOException, InvalidKeyException {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LoginUser oneUser = labWentrustService.getOneUser(loginUser.getId());
        //上面取到了，这里暂时不用
        String TId = oneUser.getTId();
        //String TId = "43";
        TokenServess tokenServess = new TokenServess();
        String tokenServe = tokenServess.getTokenServe();
        String employeeTicket = tokenServess.getEmployeeTicket(TId, "", tokenServe);
//        String tokenServe = "eyJ0eXAiOiJqd3QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI1MDcyNzUxNDc0NDM0Mzc1NjgiLCJhdWQiOiJiYXNlIiwiaXNzIjoiemh1bnplIiwiZXhwIjoxNzAxMzMxMDg4LCJpYXQiOjE3MDEzMjMyODh9.oVaQD2ZK9K6bSG8sS_eFoHI2utEe71yMCdHyEkQqtSI";
//        String employeeTicket = "455271a25f734a398258b187edc30f13803b9b73";
        HashMap<String, String> serveHashMap = new HashMap<>();
        serveHashMap.put("cardid", TId);
        serveHashMap.put("tokenServe", tokenServe);
        serveHashMap.put("employeeTicket", employeeTicket);
        return serveHashMap;
    }

    /**
     * @param token          访问口令
     * @param signatureNonce 32 位随机字符串
     * @param timestamp      时间戳（调用时的毫秒值）
     * @param page           分页页码
     * @param pageSize       分页页数
     * @param employeeId     员工 ID，与获取员工接口中的用户 ID 相同，注意：非员工编号
     * @param positionId     此参数为兼职的职务 ID，与获取职务接口中的职务 ID 相同，若员工有兼职情况，在选择到兼职职位后，会携带此参数进行筛选，即待办是会提交给相应的职务的，此参数不传时，若无兼职，则获取此员工所有消息，若有兼职，则获取主职务的职务的消息
     * @return
     * @throws NoSuchAlgorithmException
     * @throws IOException
     * @throws InvalidKeyException
     */
    @ApiOperation(value = "获取数智天研获取消息列表", notes = "获取数智天研获取消息列表")
    @PostMapping(value = "/messageList")
    public Map messageList(@RequestParam(value = "token") String token, @RequestParam(value = "signatureNonce") String signatureNonce, @RequestParam(value = "timestamp") long timestamp, @RequestParam(value = "page") Integer page, @RequestParam(value = "pageSize") Integer pageSize, @RequestParam(value = "employeeId") Integer employeeId, @RequestParam(value = "positionId", required = false) Integer positionId) throws NoSuchAlgorithmException, IOException, InvalidKeyException, ParseException {
        LoginUser loginUser = labEntrustService.byLoginUser(employeeId);
        Page<LabNotify> pages = new Page<>(page, pageSize);
        //查询已发布的十条
        labNotifyService.page(pages, new LambdaQueryWrapper<LabNotify>()
                .eq(LabNotify::getUserId, loginUser.getId())
                .eq(LabNotify::getNotStatus, "未读")
                .orderByDesc(LabNotify::getPubTime));
        TokenServess tokenServess = new TokenServess();
        //转时间格式
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ArrayList<Map> arrayList = new ArrayList<>();

        for (int i = 0; i < pages.getRecords().size(); i++) {
            HashMap<String, Object> objectObjectHashMap = new HashMap<>();
            //创建时间
            String createTime = outputFormat.format(pages.getRecords().get(i).getCreateTime());
            objectObjectHashMap.put("createTime", createTime);
            //标题
            objectObjectHashMap.put("title", pages.getRecords().get(i).getNotTitlle() + "项目:" + pages.getRecords().get(i).getItemName());
            //内容
            objectObjectHashMap.put("content", pages.getRecords().get(i).getTaskName());
            arrayList.add(objectObjectHashMap);
        }
        HashMap<String, Object> stringObjectHashMap = tokenServess.messageList(pages.getTotal(), arrayList);
        return stringObjectHashMap;
    }

    @ApiOperation(value = "数智天研获取代办任务", notes = "数智天研获取代办任务")
    @PostMapping(value = "/agencyHandlingList")
    public Map agencyHandlingList(@RequestParam(value = "token") String token, @RequestParam(value = "signatureNonce") String signatureNonce, @RequestParam(value = "timestamp") long timestamp, @RequestParam(value = "page") Integer page, @RequestParam(value = "pageSize") Integer pageSize, @RequestParam(value = "employeeId") Integer employeeId, @RequestParam(value = "positionId", required = false) Integer positionId) throws NoSuchAlgorithmException, IOException, InvalidKeyException, ParseException {
        LoginUser loginUser = labEntrustService.byLoginUser(employeeId);
        List<LabNotify> list = labNotifyService.list(new LambdaQueryWrapper<LabNotify>()
                .eq(LabNotify::getUserId, loginUser.getId())
                .and(i -> i.eq(LabNotify::getNotTitlle, "实验").or().eq(LabNotify::getNotTitlle, "实验复核"))
                .orderByDesc(LabNotify::getPubTime));
        TokenServess tokenServess = new TokenServess();
        //转时间格式
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ArrayList<Map> arrayList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getFinish() == 0) {
                HashMap<String, Object> objectObjectHashMap = new HashMap<>();
                //创建时间
                String createTime = outputFormat.format(list.get(i).getCreateTime());
                objectObjectHashMap.put("createTime", createTime);
                //标题
                objectObjectHashMap.put("title", list.get(i).getNotTitlle());
                //待办业务代码，第三方应用自行定义，当用户在页面中点击对应待办内容时，会原封不动的携带此参数跳转至应用的授权回调重定向地址
                objectObjectHashMap.put("businessCode", employeeId);
            /*第三方应用自行定义的待办参数，结合 businessCode，可以指引第三方应用跳转至待办业务详情，
            当用户在页面中点击对应待办内容时，会原封不动的携带此参数跳转至应用的授权回调重定向地址，
            长度不超过 2000 个字符*/
                if (list.get(i).getNotTitlle().equals("实验")) {
                    objectObjectHashMap.put("requestParams", "/lab/notify/items?id=" + list.get(i).getId() + "&taskId=" + list.get(i).getTaskId() + "&entrustId=" + list.get(i).getEntrustId());
                } else {
                    objectObjectHashMap.put("requestParams", "/lab/notify/items?id=" + list.get(i).getId() + "&taskId=" + list.get(i).getTaskId() + "&entrustId=" + list.get(i).getEntrustId());
                }
                arrayList.add(objectObjectHashMap);
            }

        }
        //int convertedNum = (int)list.size();
        long convertedNum = list.size();
        HashMap<String, Object> stringObjectHashMap = tokenServess.messageList(convertedNum, arrayList);
        return stringObjectHashMap;
    }

}

